/**
 * Copyright (c) 2016-2019 禾辰纵横 All rights reserved.
 *
 * https://www.ebangsoft.com
 *
 * 版权所有，侵权必究！
 */

package com.example.config;

import com.example.config.interceptor.LogHandlerInterceptor;
import com.gitee.loyo.config.interceptor.AuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    AuthInterceptor authInterceptor;

    @Bean
    public RestTemplate restTemplate() {
// 添加内容转换器,使用默认的内容转换器
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    @Bean
    OkHttpClient okHttpClient(){
        return new OkHttpClient.Builder()
            .addInterceptor(chain -> {
                Request request = chain.request();
                log.info("httpClient {} {}", request.method(), request.url().url());
                if(request.method().equalsIgnoreCase("POST")){
                    final Request copy = request.newBuilder().build();
                    final Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    log.info("Body: {}", buffer.readUtf8());
                }
                Response response = chain.proceed(request);
                if(response != null) {
                    log.info("Response {}: {}", response.code(), response.peekBody(Long.MAX_VALUE).string());
                    Headers headers = response.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        log.info("Response Header {}: {}", headers.name(i), headers.get(headers.name(i)));
                    }
                }
                return response;
            })
            .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时时间
            .readTimeout(5, TimeUnit.SECONDS)//设置读取超时时间
            .build();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogHandlerInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(authInterceptor).addPathPatterns(
            "/**/notification_stationStatus",
            "/**/notification_start_charge_result",
            "/**/notification_equip_charge_status",
            "/**/notification_stop_charge_result",
            "/**/notification_charge_order_info",
            "/**/check_charge_order"
        );
    }
}
